from flask import request, current_app
from flask_jwt_extended import jwt_required
from . import role_permission_bp
from ..services.role_permission_service import RolePermissionService
from ..services.role_service import RoleService
from ..services.permission_service import PermissionService
from ..utils.response import success_response, error_response
from ..middlewares.permission import check_permission

@role_permission_bp.route('', methods=['GET'])
@jwt_required()
@check_permission()
def get_role_permissions():
    """获取角色权限关系列表"""
    try:
        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('size', 10, type=int)
        role_id = request.args.get('role_id', None, type=int)
        
        result = RolePermissionService.get_role_permission_list(
            page=page, per_page=per_page, role_id=role_id
        )
        return success_response(data=result)
    except Exception as e:
        current_app.logger.error(f"获取角色权限关系列表失败: {str(e)}")
        return error_response(message="获取角色权限关系列表失败")

@role_permission_bp.route('', methods=['POST'])
@jwt_required()
@check_permission()
def create_role_permission():
    """创建角色权限关系"""
    try:
        data = request.get_json()
        if not data or 'role_id' not in data or 'permission_id' not in data:
            return error_response(message="角色ID和权限ID不能为空")
        
        # 检查角色是否存在
        role = RoleService.get_role_by_id(data['role_id'])
        if not role:
            return error_response(message="角色不存在", code=404)
        
        # 检查权限是否存在
        permission = PermissionService.get_permission_by_id(data['permission_id'])
        if not permission:
            return error_response(message="权限不存在", code=404)
        
        # 检查关系是否已存在
        if RolePermissionService.check_role_permission_exists(data['role_id'], data['permission_id']):
            return error_response(message="角色权限关系已存在")
        
        role_permission = RolePermissionService.create_role_permission(
            data['role_id'], data['permission_id']
        )
        return success_response(message="创建成功", data=role_permission.to_dict())
    except Exception as e:
        current_app.logger.error(f"创建角色权限关系失败: {str(e)}")
        return error_response(message="创建角色权限关系失败")

@role_permission_bp.route('/<int:id>', methods=['GET'])
@jwt_required()
@check_permission()
def get_role_permission(id):
    """获取指定角色权限关系详情"""
    try:
        role_permission = RolePermissionService.get_role_permission_by_id(id)
        if not role_permission:
            return error_response(message="角色权限关系不存在", code=404)
        
        # 获取关联信息
        role = RoleService.get_role_by_id(role_permission.role_id)
        permission = PermissionService.get_permission_by_id(role_permission.permission_id)
        
        data = role_permission.to_dict()
        if role and permission:
            data.update({
                'role_name': role.role_name,
                'role_code': role.role_code,
                'permission_name': permission.permission_name,
                'permission_code': permission.permission_code
            })
        
        return success_response(data=data)
    except Exception as e:
        current_app.logger.error(f"获取角色权限关系详情失败: {str(e)}")
        return error_response(message="获取角色权限关系详情失败")

@role_permission_bp.route('/<int:id>', methods=['DELETE'])
@jwt_required()
@check_permission()
def delete_role_permission(id):
    """删除角色权限关系"""
    try:
        role_permission = RolePermissionService.get_role_permission_by_id(id)
        if not role_permission:
            return error_response(message="角色权限关系不存在", code=404)
        
        RolePermissionService.delete_role_permission(role_permission)
        return success_response(message="删除成功")
    except Exception as e:
        current_app.logger.error(f"删除角色权限关系失败: {str(e)}")
        return error_response(message="删除角色权限关系失败")

@role_permission_bp.route('/batch', methods=['POST'])
@jwt_required()
@check_permission()
def batch_update_role_permissions():
    """批量更新角色权限关系"""
    try:
        data = request.get_json()
        if not data or 'role_id' not in data or 'permission_ids' not in data:
            return error_response(message="角色ID和权限ID列表不能为空")
        
        # 检查角色是否存在
        role = RoleService.get_role_by_id(data['role_id'])
        if not role:
            return error_response(message="角色不存在", code=404)
        
        # 检查权限是否都存在
        for permission_id in data['permission_ids']:
            permission = PermissionService.get_permission_by_id(permission_id)
            if not permission:
                return error_response(message=f"权限ID {permission_id} 不存在", code=404)
        
        success = RolePermissionService.batch_update_role_permissions(
            data['role_id'], data['permission_ids']
        )
        if success:
            return success_response(message="批量更新成功")
        return error_response(message="批量更新失败")
    except Exception as e:
        current_app.logger.error(f"批量更新角色权限关系失败: {str(e)}")
        return error_response(message="批量更新角色权限关系失败") 